package com.xb.system.controller;


import com.xb.model.domain.entity.FileUpload;
import com.xb.system.common.result.Result;
import com.xb.system.mapper.db1.FileUploadMapper;
import com.xb.system.service.SysDocService;
import com.xb.system.service.impl.LocalFileStorageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author cjl
 * @since 2024-05-08
 */
@Api(tags = "文件下载")
@RestController
@Slf4j
public class SysDocController {

    @Autowired
    private LocalFileStorageService fileStorageService;
    @Autowired
    private FileUploadMapper fileUploadMapper;


    @ApiOperation(value = "结果文件下载", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
    @GetMapping("/admin/system/sysDoc/download/result/{id}")
    public ResponseEntity<InputStreamResource> downloadResult(@PathVariable Long id) throws IOException {
        FileUpload fileUpload = fileUploadMapper.selectById(id);
        if (fileUpload == null || !fileStorageService.fileExists(fileUpload.getResultFilePath())) {
            throw new FileNotFoundException("结果文件不存在");
        }
        InputStream inputStream = fileStorageService.getFileStream(fileUpload.getResultFilePath());
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileUpload.getFileName())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new InputStreamResource(inputStream));
    }
    
    @ApiOperation(value = "模板文件下载")
    @GetMapping("/admin/system/sysDoc/download-template")
    public void downloadTemplate(HttpServletResponse response) throws IOException {
        log.info("开始下载模板文件...");
        // 从资源目录获取模板文件
        ClassPathResource resource = new ClassPathResource("模板.xlsx");
        
        if (!resource.exists()) {
            log.error("模板文件不存在: 模板.xlsx");
            throw new FileNotFoundException("模板文件不存在");
        }
        
        log.info("找到模板文件，文件大小: {} bytes", resource.contentLength());
        
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = "筛查模板.xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
        
        // 直接写入响应流
        try (InputStream inputStream = resource.getInputStream();
             ServletOutputStream outputStream = response.getOutputStream()) {
            
            FileCopyUtils.copy(inputStream, outputStream);
            outputStream.flush();
            log.info("模板文件下载完成");
        } catch (IOException e) {
            log.error("模板文件下载失败", e);
            throw e;
        }
    }
    
    /**
     * 公开访问的模板下载接口
     */
    @ApiOperation(value = "公开模板下载")
    @GetMapping("/public/template/download")
    public void downloadTemplatePublic(HttpServletResponse response) throws IOException {
        log.info("开始下载公开模板文件...");
        // 从资源目录获取模板文件
        ClassPathResource resource = new ClassPathResource("模板.xlsx");
        
        if (!resource.exists()) {
            log.error("模板文件不存在: 模板.xlsx");
            throw new FileNotFoundException("模板文件不存在");
        }
        
        log.info("找到模板文件，文件大小: {} bytes", resource.contentLength());
        
        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*"); // 允许跨域
        String fileName = "筛查模板.xlsx";
        String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment; filename=" + encodedFileName);
        
        // 直接写入响应流
        try (InputStream inputStream = resource.getInputStream();
             ServletOutputStream outputStream = response.getOutputStream()) {
            
            FileCopyUtils.copy(inputStream, outputStream);
            outputStream.flush();
            log.info("公开模板文件下载完成");
        } catch (IOException e) {
            log.error("公开模板文件下载失败", e);
            throw e;
        }
    }
}

